#include <iostream>
#include <string>
#include <queue>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>
#include <cstring>
#include <cstdlib>

#define BACKLOG 5
#define NUM 5

class Handler
{
public:
    Handler() {}
    ~Handler() {}
    void operator()(int sock, std::string client_ip, int client_port)
    {
        char buffer[1024];
        while (true)
        {
            ssize_t size = read(sock, buffer, sizeof(buffer) - 1);
            if (size > 0)
            { // 读取成功
                buffer[size] = '\0';
                std::cout << client_ip << ":" << client_port << "# " << buffer << std::endl;
                write(sock, buffer, size);
            }
            else if (size == 0)
            { // 对端关闭连接
                std::cout << client_ip << ":" << client_port << " close!" << std::endl;
                break;
            }
            else
            { // 读取失败
                std::cerr << sock << " read error!" << std::endl;
                break;
            }
        }
        close(sock); // 归还文件描述符
        std::cout << client_ip << ":" << client_port << " service done!" << std::endl;
    }
};

class Task
{
public:
    Task() {}
    Task(int sock, std::string client_ip, int client_port)
        : _sock(sock), _client_ip(client_ip), _client_port(client_port) {}
    ~Task() {}

    void Run()
    {
        _handler(_sock, _client_ip, _client_port);
    }

private:
    int _sock;
    std::string _client_ip;
    int _client_port;
    Handler _handler;
};

template <class T>
class ThreadPool
{
private:
    bool IsEmpty()
    {
        return _task_queue.size() == 0;
    }
    void LockQueue()
    {
        pthread_mutex_lock(&_mutex);
    }
    void UnLockQueue()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void Wait()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    void WakeUp()
    {
        pthread_cond_signal(&_cond);
    }

public:
    ThreadPool(int num = NUM)
        : _thread_num(num)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

    static void *Routine(void *arg)
    {
        pthread_detach(pthread_self());
        ThreadPool *self = (ThreadPool *)arg;
        while (true)
        {
            self->LockQueue();
            while (self->IsEmpty())
            {
                self->Wait();
            }
            T task;
            self->Pop(task);
            self->UnLockQueue();
            task.Run();
        }
    }

    void ThreadPoolInit()
    {
        pthread_t tid;
        for (int i = 0; i < _thread_num; i++)
        {
            pthread_create(&tid, nullptr, Routine, this);
        }
    }

    void Push(const T &task)
    {
        LockQueue();
        _task_queue.push(task);
        UnLockQueue();
        WakeUp();
    }

    void Pop(T &task)
    {
        task = _task_queue.front();
        _task_queue.pop();
    }

private:
    std::queue<T> _task_queue;
    int _thread_num;
    pthread_mutex_t _mutex;
    pthread_cond_t _cond;
};

class TcpServer
{
public:
    TcpServer(int port)
        : _listen_sock(-1), _port(port), _tp(nullptr) {}

    void InitServer()
    {
        _listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listen_sock < 0)
        {
            std::cerr << "socket error" << std::endl;
            exit(2);
        }

        struct sockaddr_in local;
        memset(&local, '\0', sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        if (bind(_listen_sock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            std::cerr << "bind error" << std::endl;
            exit(3);
        }

        if (listen(_listen_sock, BACKLOG) < 0)
        {
            std::cerr << "listen error" << std::endl;
            exit(4);
        }

        _tp = new ThreadPool<Task>();
    }

    void Start()
    {
        _tp->ThreadPoolInit();
        for (;;)
        {
            struct sockaddr_in peer;
            memset(&peer, '\0', sizeof(peer));
            socklen_t len = sizeof(peer);
            int sock = accept(_listen_sock, (struct sockaddr *)&peer, &len);
            if (sock < 0)
            {
                std::cerr << "accept error, continue next" << std::endl;
                continue;
            }
            std::string client_ip = inet_ntoa(peer.sin_addr);
            int client_port = ntohs(peer.sin_port);
            std::cout << "get a new link->" << sock << " [" << client_ip << "]:" << client_port << std::endl;

            Task task(sock, client_ip, client_port);
            _tp->Push(task);
        }
    }

private:
    int _listen_sock;
    int _port;
    ThreadPool<Task> *_tp;
};

void Usage(std::string proc)
{
    std::cout << "Usage: " << proc << " port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    int port = atoi(argv[1]);
    TcpServer* svr = new TcpServer(port);

    svr->InitServer();
    svr->Start();
    
    return 0;
}